package searchEngine;
import java.util.HashSet;
import java.util.Iterator;
import java.util.regex.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class SearchEngine {
	
	public static HashSet<StringBuffer> search(String searchExpr, String Url ) throws MalformedURLException, IOException {
		URL u = new URL(Url);
		return search(searchExpr, u);
	}	
	public static HashSet<StringBuffer> search(String searchExpr, URL Url ) throws IOException {	
		
		Pattern agentBlock = Pattern.compile(searchExpr);
		StringBuffer urlSource = utils.ReaderFactory.readUrlData(Url, "ISO-8859-1");
		Matcher agentsMatcher = agentBlock.matcher(urlSource);
		HashSet<StringBuffer> searchResults = new HashSet<StringBuffer>();
		
		while (agentsMatcher.find()) {
			searchResults.add(new StringBuffer(agentsMatcher.group()));
		}
		
		return searchResults;
	}
	public static HashSet<StringBuffer> search(String searchExpr, HashSet<URL> urlList) throws IOException {	
		Iterator<URL> iterator = urlList.iterator();
		HashSet<StringBuffer> searchResults = new HashSet<StringBuffer>();
		Pattern agentBlock = Pattern.compile("false");
		Matcher agentsMatcher = agentBlock.matcher("");;
		try{
			agentBlock = Pattern.compile(searchExpr);
		}catch(PatternSyntaxException e){
			searchResults.add(new StringBuffer("Exception:" + e.getMessage().toString()+ " caused by: \n" + searchExpr));
		}
		if(!agentBlock.pattern().equals("false")){
			while(iterator.hasNext()){
				try{
					StringBuffer urlSource = utils.ReaderFactory.readUrlData(iterator.next(), "ISO-8859-1");
					agentsMatcher = agentBlock.matcher(urlSource);
				}catch(IOException e){
					searchResults.add(new StringBuffer("Exception:" + e.getMessage().toString()+ " caused by: \n" + searchExpr));
				}
				while (agentsMatcher.find()) {
					searchResults.add(new StringBuffer(agentsMatcher.group()));
				}
			}
		}
		return searchResults;
	}
}
